import serial
import time
import json
import os
from datetime import datetime

# 固定配置
PORT = '/dev/ttyACM0'
BAUDRATE = 115200
SAVE_FILE = 'sensor_data.json'

def parse_sensor_data(raw_data):
    """
    Parse raw sensor data and convert to JSON format
    
    Args:
        raw_data (str): Raw data string read from serial port
        
    Returns:
        dict: Dictionary containing timestamp and sensor data, returns None if data is invalid
    """
    # Only process data containing temperature or humidity
    if "Temperature" not in raw_data and "Humidity" not in raw_data:
        return None
    
    # 创建数据记录
    data = {
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    try:
        # 提取温度
        if "Temperature" in raw_data:
            temp_str = raw_data.split("Temperature:")[1].split(",")[0].strip()
            data["temperature"] = float(temp_str.replace("C", ""))
        
        # 提取湿度
        if "Humidity" in raw_data:
            humid_str = raw_data.split("Humidity:")[1].split(",")[0].strip()
            data["humidity"] = float(humid_str.replace("%", ""))
        
        return data
    except (ValueError, IndexError) as e:
        print(f"Error parsing sensor data: {e}")
        return None

def save_sensor_data(sensor_records, new_data):
    """
    Save sensor data to JSON file
    
    Args:
        sensor_records (list): Existing list of sensor data records
        new_data (dict): New sensor data
        
    Returns:
        list: Updated list of sensor data records
    """
    if new_data is None:
        return sensor_records
    
    # 添加到记录列表
    sensor_records.append(new_data)
    
    # 限制记录数量为最新的100条
    if len(sensor_records) > 100:
        sensor_records = sensor_records[-100:]
    
    # 保存所有数据到文件
    try:
        with open(SAVE_FILE, 'w') as f:
            json.dump(sensor_records, f, indent=2)
        print(f"Saved sensor data: {new_data}")
    except Exception as e:
        print(f"Error saving data: {e}")
    
    return sensor_records

def sensor_data_reader():
    print(f"Connecting to {PORT}...")
    
    # 读取现有数据（如果有）
    sensor_records = []
    if os.path.exists(SAVE_FILE):
        try:
            with open(SAVE_FILE, 'r') as f:
                sensor_records = json.load(f)
                if not isinstance(sensor_records, list):
                    sensor_records = []
        except:
            sensor_records = []
    
    try:
        # 连接串口
        ser = serial.Serial(PORT, BAUDRATE, timeout=1)
        print(f"Connected successfully")
        
        # 读取并处理数据
        while True:
            if ser.in_waiting > 0:
                raw_data = ser.readline().decode('utf-8').strip()
                print(raw_data)
                
                # 解析传感器数据
                parsed_data = parse_sensor_data(raw_data)
                
                # 保存数据
                sensor_records = save_sensor_data(sensor_records, parsed_data)
                
            time.sleep(0.1)
    
    except KeyboardInterrupt:
        print("Program stopped")
    finally:
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("Serial port closed")

if __name__ == "__main__":
    sensor_data_reader() 